<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间" prop="investigationTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.investigationTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['risk:investigation:add']"
        >治理上报</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['risk:investigation:edit']"
        >整改治理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['risk:investigation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['risk:investigation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="investigationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="时间" align="center" prop="investigationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.investigationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="隐患类型" align="center" prop="dangersType" :formatter="dangersTypeFormat"/>
      <el-table-column label="隐患等级" align="center" prop="dangersGrade" :formatter="dangersGradeFormat"/>
      <el-table-column label="主体单位" align="center" prop="mainUnit" />
      <el-table-column label="隐患来源" align="center" prop="dangersSource" />
      <el-table-column label="隐患内容" align="center" prop="dangersContent" />
      <el-table-column label="涉及业务" align="center" prop="involvingBusiness" :formatter="involvingBusinessFormat"/>
      <el-table-column label="监管单位(人员)" align="center" prop="regulatoryAuthorities" :formatter="regulatoryAuthoritiesFormat"/>
      <el-table-column label="整改责任人" align="center" prop="personLiable" />
      <el-table-column label="治理措施(方案)" align="center" prop="governanceMeasures" />
      <el-table-column label="等效措施(管控措施)" align="center" prop="equivalentMeasures" />
      <el-table-column label="治理时限" align="center" prop="governanceDeadline" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.governanceDeadline, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="治理进度" align="center" prop="governanceProgress" :formatter="governanceProgressFormat" />
      <el-table-column label="治理效果(验收标准)" align="center" prop="governanceEffectiveness" />
      <el-table-column label="原因分析" align="center" prop="causeAnalysis" />
      <el-table-column label="备注" align="center" prop="remark" />
<!--      <el-table-column label="整改图片" align="center" prop="picture" />-->
<!--      <el-table-column label="备用" align="center" prop="remarkSpare" />-->
<!--      <el-table-column label="备用1" align="center" prop="remarkSpare1" />-->
<!--      <el-table-column label="备用2" align="center" prop="remarkSpare2" />-->
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['risk:investigation:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['risk:investigation:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改安全生产隐患排查治理清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="时间" prop="investigationTime">
          <el-date-picker clearable size="small"
            v-model="form.investigationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择时间" :disabled="form.id"  style="width: 100%">
          </el-date-picker>
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
        <el-form-item label="隐患类型" prop="dangersType">
<!--          <el-input v-model="form.dangersType" placeholder="请输入隐患类型" :disabled="form.id"/>-->
          <el-select v-model="form.dangersType" placeholder="请输入隐患类型" :disabled="form.id"  style="width: 100%">
            <el-option
              v-for="dict in dangersTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="隐患等级" prop="dangersGrade">
          <el-select v-model="form.dangersGrade" placeholder="请选择隐患等级" :disabled="form.id"  style="width: 100%">
            <el-option
              v-for="dict in dangersGradeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
<!--          <el-input v-model="form.dangersGrade" placeholder="请输入隐患等级" :disabled="form.id"/>-->
<!--          <div style="margin-top: 5px;">-->
<!--            <el-link style="font-size: 10px ; color: red" target="_blank" @click="showHelp">查看帮助文档</el-link>-->
<!--          </div>-->
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
        <el-form-item label="主体单位" prop="mainUnit">
          <treeselect v-model="form.mainUnit" :options="deptOptions" :show-count="true" placeholder="请输入主体单位" :disabled="form.id"  style="width: 100%"/>
<!--          <el-input v-model="form.mainUnit" placeholder="请输入主体单位" :disabled="form.id"/>-->
        </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="隐患来源" prop="dangersSource">
          <el-input v-model="form.dangersSource"  type="textarea" placeholder="请输入隐患来源" :disabled="form.id"/>
        </el-form-item>
        <el-form-item label="隐患内容" prop="dangersContent">
          <el-input v-model="form.dangersContent"  type="textarea" placeholder="请输入隐患内容" :disabled="form.id"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="涉及业务" prop="involvingBusiness">
<!--          <el-input v-model="form.involvingBusiness" placeholder="请输入涉及业务" :disabled="form.id"/>-->
          <el-select v-model="form.involvingBusiness" placeholder="请选择涉及业务" :disabled="form.id"  style="width: 100%">
            <el-option
              v-for="dict in involvingBusinessOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
        <el-form-item label="监管单位(人员)" prop="regulatoryAuthorities">
          <treeselect v-model="form.regulatoryAuthorities" :options="deptOptions" :show-count="true" placeholder="请输入主体单位" :disabled="form.id"  style="width: 100%"/>

<!--          <el-select v-model="form.regulatoryAuthorities" placeholder="请选择监管单位(人员)" :disabled="form.id"  style="width: 100%">-->
<!--            <el-option-->
<!--              v-for="dict in regulatoryAuthoritiesOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictLabel"-->
<!--              :value="dict.dictValue"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--          <el-input v-model="form.regulatoryAuthorities" placeholder="请输入监管单位(人员)" :disabled="form.id"/>-->
        </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="整改责任人" prop="personLiable">
          <el-select  v-model="form.personLiable" filterable placeholder="选择整改责任人"  :disabled="form.id"  style="width: 100%">
            <el-option
              v-for="user in filteredUsers"
              :key="user.userId+''"
              :label="user.nickName "
              :value="user.userId+''">
            </el-option>
          </el-select>
<!--          <el-input v-model="form.personLiable" placeholder="请输入整改责任人" :disabled="form.id"/>-->
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="治理时限" prop="governanceDeadline">
              <el-date-picker clearable size="small"
                              v-model="form.governanceDeadline"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择治理时限" :disabled="form.id"  style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="治理措施(方案)" prop="governanceMeasures">
          <el-input v-model="form.governanceMeasures" type="textarea" placeholder="请输入治理措施(方案)" :disabled="form.id"/>
        </el-form-item>
        <el-form-item label="等效措施(管控措施)" prop="equivalentMeasures">
          <el-input v-model="form.equivalentMeasures" type="textarea" placeholder="请输入等效措施(管控措施)" />
        </el-form-item>
        <el-form-item label="治理进度" prop="governanceProgress">
          <el-select v-model="form.governanceProgress" placeholder="请选择治理进度"  style="width: 100%">
            <el-option
              v-for="dict in governanceProgressOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="displayItem" label="治理效果(验收标准)" prop="governanceEffectiveness">
          <el-input v-model="form.governanceEffectiveness"  type="textarea" placeholder="请输入治理效果(验收标准)" />
        </el-form-item>
        <el-form-item label="原因分析" prop="causeAnalysis">
          <el-input v-model="form.causeAnalysis" type="textarea" placeholder="请输入原因分析" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item v-if="displayItem" label="整改图片">
          <imageUpload v-model="form.picture"/>
        </el-form-item>
<!--        <el-form-item label="备用" prop="remarkSpare">-->
<!--          <el-input v-model="form.remarkSpare" placeholder="请输入备用" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备用1" prop="remarkSpare1">-->
<!--          <el-input v-model="form.remarkSpare1" placeholder="请输入备用1" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备用2" prop="remarkSpare2">-->
<!--          <el-input v-model="form.remarkSpare2" placeholder="请输入备用2" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInvestigation, getInvestigation, delInvestigation, addInvestigation, updateInvestigation, exportInvestigation } from "@/api/risk/investigation";
import { getCurrentUser, listUserNoPage } from '@/api/system/user'
import Treeselect from '@riophae/vue-treeselect'
import { treeselect } from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Investigation",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安全生产隐患排查治理清单表格数据
      investigationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      deptId: "",
      // 治理进度字典
      governanceProgressOptions: [],
      dangersGradeOptions: [],
      dangersTypeOptions: [],
      involvingBusinessOptions: [],
      regulatoryAuthoritiesOptions: [],
      // 部门树选项
      deptOptions: undefined,
      filteredUsers:[],
      displayItem: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        investigationTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        investigationTime: [
          { required: true, message: "时间不能为空", trigger: "blur" }
        ],
        dangersType: [
          { required: true, message: "隐患类型不能为空", trigger: "blur" }
        ],
        dangersGrade: [
          { required: true, message: "隐患等级不能为空", trigger: "blur" }
        ],
        dangersSource: [
          { required: true, message: "隐患来源不能为空", trigger: "blur" }
        ],
        mainUnit: [
          { required: true, message: "主体单位不能为空", trigger: "blur" }
        ],
        dangersContent: [
          { required: true, message: "隐患内容不能为空", trigger: "blur" }
        ],
        involvingBusiness: [
          { required: true, message: "涉及业务不能为空", trigger: "blur" }
        ],
        regulatoryAuthorities: [
          { required: true, message: "监管单位(人员)不能为空", trigger: "blur" }
        ],
        personLiable: [
          { required: true, message: "整改责任人不能为空", trigger: "blur" }
        ],
        governanceMeasures: [
          { required: true, message: "治理措施(方案)不能为空", trigger: "blur" }
        ],
        equivalentMeasures: [
          { required: true, message: "等效措施(管控措施)不能为空", trigger: "blur" }
        ],
        governanceDeadline: [
          { required: true, message: "治理时限不能为空", trigger: "blur" }
        ],
        governanceProgress: [
          { required: true, message: "治理进度不能为空", trigger: "blur" }
        ],
        causeAnalysis: [
          { required: true, message: "原因分析不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getCurrentUser();
    this.fetchUsers();
    this.getList();
    this.getDicts("governance_progress").then(response => {
      this.governanceProgressOptions = response.data;
    });
    this.getDicts("dangers_grade").then(response => {
      this.dangersGradeOptions = response.data;
    });
    this.getDicts("dangers_type").then(response => {
      this.dangersTypeOptions = response.data;
    });
    this.getDicts("involving_business").then(response => {
      this.involvingBusinessOptions = response.data;
    });
    this.getDicts("regulatory_authorities").then(response => {
      this.regulatoryAuthoritiesOptions = response.data;
    });
    this.getTreeselect();
  },
  methods: {
    /** 查询安全生产隐患排查治理清单列表 */
    getList() {
      this.loading = true;
      listInvestigation(this.queryParams).then(response => {
        this.investigationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
        // console.log('this.deptOptions:' + JSON.stringify(this.deptOptions))
      });
    },
    // 治理进度字典翻译
    governanceProgressFormat(row, column) {
      return this.selectDictLabel(this.governanceProgressOptions, row.governanceProgress);
    },
    dangersGradeFormat(row, column) {
      return this.selectDictLabel(this.dangersGradeOptions, row.dangersGrade);
    },
    dangersTypeFormat(row, column) {
      return this.selectDictLabel(this.dangersTypeOptions, row.dangersType);
    },
    involvingBusinessFormat(row, column) {
      return this.selectDictLabel(this.involvingBusinessOptions, row.involvingBusiness);
    },
    regulatoryAuthoritiesFormat(row, column) {
      return this.selectDictLabel(this.regulatoryAuthoritiesOptions, row.regulatoryAuthorities);
    },
    fetchUsers() {
      this.loading=true;
      listUserNoPage().then(response => {
          this.filteredUsers = response.rows;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        investigationTime: null,
        dangersType: null,
        dangersGrade: null,
        mainUnit: null,
        dangersSource: null,
        dangersContent: null,
        involvingBusiness: null,
        regulatoryAuthorities: null,
        personLiable: null,
        governanceMeasures: null,
        equivalentMeasures: null,
        governanceDeadline: null,
        governanceProgress: null,
        governanceEffectiveness: null,
        causeAnalysis: null,
        remark: null,
        picture: null,
        remarkSpare: null,
        remarkSpare1: null,
        remarkSpare2: null,
        createBy: null,
        createTime: null,
        deptId: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    getCurrentUser() {
      let currentUser = this.$store.state.user;
      getCurrentUser(currentUser.userId).then(response => {
        this.deptId = response.data.deptId
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.displayItem = false;
      this.form.dangersGrade = "1"
      this.form.regulatoryAuthorities = this.deptId;
      this.title = "添加安全生产隐患排查治理清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInvestigation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.displayItem = true;
        this.title = "修改安全生产隐患排查治理清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInvestigation(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInvestigation(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除安全生产隐患排查治理清单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInvestigation(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有安全生产隐患排查治理清单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          // return exportInvestigation(queryParams);
        this.download('/risk/investigation/export', {
          ...this.queryParams
        }, `安全生产隐患排查治理清单.xlsx`)
        this.exportLoading = false;
        }).then(response => {
          // this.download(response.msg);
          // this.exportLoading = false;
        }).catch(() => {});
    },
    showHelp() {
      // this.showHelpModal = true;
      const helpDocPath = process.env.BASE_URL + '集团公司安全生产重大隐患判定标准（试行）重大隐患判定标准帮助文档.pdf';
      window.open(helpDocPath, '_blank');
    },
  }
};
</script>
